package com.hdwx.weike.Utils;

import java.sql.*;

public class JdbcUtils {
    static {
        //注册驱动，加载driver类的静态代码块
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //连接到mysql服务器
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/weike", "root", "999pyp");
    }
    //关闭资源
    public static void close(ResultSet set,Statement statement,Connection con){
        if(set != null){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //关闭资源
    public static void close(ResultSet set){
        Connection con=null;
        Statement statement=null;
        if(set!=null){
            try {
                //通过结果集获取预处理对象
                statement=set.getStatement();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                //通过预处理对象获取连接对象
                con=statement.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(set, statement, con);
    }
}
